<?php

// The constructor takes one or more Cisco-style denoted subnets (string or array)
// The match-method takes a string (ip address) and
// returns bool wether the ip is within one of the given subnets
class subnetMatcher {
	
	var $subnets = array();

	function subnetMatcher($subnet) {
		if(is_array($subnet)) {
			$this->subnets = $subnet;
		} else {
			$this->subnets[] = $subnet;
		}
	}

	function match($subject) {
		foreach($this->subnets as $subnet) {
			$boo = $this->_match($subject, $subnet);
			if($boo) return true;
		}
		return false;
	}

	function _match($subject, $net) {
		$parts = explode("/", $net);
		$netmask = $parts[1];

		$subject = sprintf('%032b', ip2long($subject));
		$network = sprintf('%032b', ip2long($parts[0]));

		$netbits = substr($network, 0, $netmask);
		$subbits = substr($subject, 0, $netmask);

		// USE TYPESAFE MATCHING! PHP SUCKS!
		return($netbits === $subbits);
	}
}
